package org.wjk.handler;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.wjk.pojo.vo.ResponseRes;
import org.wjk.utils.JedisUtils;
import org.wjk.utils.JwtTokenUtils;
import org.wjk.utils.ResponseUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

@Component
@Slf4j
@RequiredArgsConstructor
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private final JwtTokenUtils tokenUtils;
    private final JedisUtils jedisUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        /*给前端返回JwtToken，提醒用户认证成功，删除redis里当前用户登陆失败的次数*/
        /*第一步：获取当前登录用户的用户名*/
        String username = request.getParameter("username");
        log.debug("当前登陆的用户的用户名为{}", username);
        /*第二布 校验验证码
         * 1.从request里获取captcha的值
         * 2.从request里获取对应的key： captchaKey*/
        String captcha = (request.getParameter("captcha")).toLowerCase(Locale.ROOT);
        String captchaKey = request.getParameter("captchaKey");
        log.debug("当前登陆的用户的captcha为" + captcha);
        log.debug("当前登陆的用户的captchaKey为{}", captchaKey);
        /*从redis里取对应的value*/
        String value = jedisUtils.get(captchaKey);
        log.debug("对应的value为" + value);
        /*校验验证码
         * 如果redis里的验证码为null说明验证码过期，提示用户验证码已过期，点击刷新后重新输入
         * 如果有验证码，校验前端输入验证码是否一致，
         * 如果一致：开始构建token返回登录成功条件
         * 如果不一致：提示用户，您输入的验证码错误请重新输入*/
        if (value == null) {
            ResponseUtils.convertToJson(response, ResponseRes.failure(5001, "验证码已过期，点击刷新后重新输入", null));
            return;
        }
        if (!value.equals(captcha)) {
            ResponseUtils.convertToJson(response, ResponseRes.failure(5001,"您输入的验证码错误请重新输入",null));
            return;
        }
        /*第三步 构建token*/
        String token = tokenUtils.getJwtToken(username);
        log.debug("当前{}的用户获取的tokan是{}", username, token);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("header", tokenUtils.getProps().getHeader());
        tokenMap.put("head", tokenUtils.getProps().getHead());
        /*往前端相应的方法5001失败，2000成功*/
        ResponseUtils.convertToJson(response, ResponseRes.success("登录成功！", tokenMap));
        jedisUtils.delete(username);


    }
}